//商品搜索页
var server = require('../../utils/server');
var common = require('../../utils/common');
const app = getApp();
Page({
  data: {
    showRecentSearch: true,
    recentWords: [],
    mostWords: [],
    resultList: [],
    searchValue: "",
    cartNum: 0,
    keywords: '',
    storeId: "",
    showDetail: false,
    goodsDetail: [],
    showWeightTit: false,
    showDelPop: false,
    showLoginPop: false,
    isLogin: true,
    isDisableLog: false
  },
  onLoad() {},
  onShow() {
    app.globalData.isFromCart = false;

    this.getHistoryWord();
    var that = this;
    wx.getStorage({
      key: 'storeId',
      success: function (resp) {
        that.data.storeId = resp.data;
        wx.getStorage({
          key: 'sso',
          success: ret => {
            console.log(ret)
            that.setData({
              isLogin: true
            })
            that.getRecommendGoods();
          },
          fail: ret => {
            that.setData({
              isLogin: false
            })
          }
        })
        that.getCartNum();
        if (that.data.searchValue != '' && that.data.storeId != '') {
          server.postJSON(common.storePath + 'store/goodssearch', {
            "store_id": that.data.storeId,
            "keyword": that.data.searchValue
          }, res => {
            if (res.data.errno == "0") {
              common.hideLoading();
              var data = res.data.data;
              wx.reportAnalytics('search_goods', {
                search_key: that.data.searchValue,
                search_result: data.list,
                storeid: that.data.storeId,
                storename: data.store.name
              });
              for (var j = 0; j < data.list.length; j++) {
                data.list[j].isCanAdd = true;
                data.list[j].isCanReduce = true;
              }
              that.setData({
                resultList: data.list,
                showRecentSearch: false
              })
            } else {
              common.showErrorToast(res.data.errmsg);
            }
          })
        }
      },
      fail: res => {
        wx.getStorage({
          key: 'sso',
          success: res => {
            console.log(res)
            this.setData({
              isLogin: true
            })
          },
          fail: res => {
            this.setData({
              isLogin: false
            })
            console.log(this.data.isLogin)
          }
        })
      }
    })

  },
  //获取购物车数量
  getCartNum() {
    server.postJSON(common.storePath + 'cart/goodsnum', {
      "store_id": this.data.storeId,
      "is_deliverable": 0
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          cartNum: res.data.data.cart.num,
          cartPrice: res.data.data.cart.amount
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }

    })
  },
  backToShop() {
    wx.navigateBack()
  },
  getSearchvalue(e) {
    if (e.detail.value == "") {
      this.getHistoryWord();
      this.setData({
        showRecentSearch: true,
        searchValue: e.detail.value
      })
    } else {
      this.setData({
        keywords: e.detail.value,
        searchValue: e.detail.value
      })
    }

  },
  searchByHistory(e) {
    var keyword = e.currentTarget.dataset.id;
    common.showLoading("搜索中...");
    this.searchProduct(keyword);
    this.setData({
      searchValue: keyword
    })
  },
  searchByInput() {
    var keyword = this.data.searchValue;
    common.showLoading("搜索中...");
    this.searchProduct(keyword);
  },
  searchProduct(keyword) {
    if (keyword != "" && keyword != undefined) {
      server.postJSON(common.storePath + 'store/goodssearch', {
        "store_id": this.data.storeId,
        "keyword": keyword
      }, res => {
        if (res.data.errno == "0") {
          common.hideLoading();
          var data = res.data.data;
          wx.reportAnalytics('search_goods', {
            search_key: keyword,
            search_result: data.list,
            storeid: this.data.storeId,
            storename: data.store.name
          });
          for (var j = 0; j < data.list.length; j++) {
            data.list[j].isCanAdd = true;
            data.list[j].isCanReduce = true;
          }
          this.setData({
            resultList: data.list,
            showRecentSearch: false,
            searchValue: keyword
          })
          // 自定义分析
          console.log(keyword, data.list)
          this.storageHistoryWords(keyword)
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else {
      common.showToast("搜索关键字不能为空")
    }

  },
  storageHistoryWords(words) {
    wx.getStorage({
      key: 'historyWordsArray',
      success: res => {
        var data = (res.data);
        if (data.length < 10 && data.indexOf(words) == -1) {
          data.push(words)
        } else if (data.length == 10 && data.indexOf(words) == -1) {
          data.splice(0, 1, words)
        }
        wx.setStorage({
          key: 'historyWordsArray',
          data: Array.from(new Set(data))
        })
      },
      fail: res => {
        let data = res.data;
        data = new Array();
        data.push(words)
        wx.setStorage({
          key: 'historyWordsArray',
          data: Array.from(new Set(data)),
        })
      }
    })
  },
  getHistoryWord() {
    var recentWords = wx.getStorageSync('historyWordsArray');
    if (recentWords != undefined && recentWords != "") {
      this.setData({
        recentWords: recentWords
      })
    }
  },
  // 添加购物车
  addCount(e) {
    this.addCart(e);
  },
  addCart(e) {
    console.log(e)
    var curtarget = e.currentTarget.dataset;
    let goodsIndex = curtarget.index;
    let name = curtarget.name;
    let goodprice = curtarget.price;
    let goodsnum = curtarget.goodsnum;
    var cartList = this.data.resultList;
    cartList[goodsIndex].isCanAdd = false;
    this.setData({
      resultList: cartList
    })
    server.postJSON(common.storePath + 'cart/addgoods/', {
      "store_id": this.data.storeId,
      "goods_id": curtarget.id,
      "trace_id": ""
    }, res => {
      if (res.data.errno == "0") {
        common.showErrorToast("添加成功");
        this.setData({
          ['resultList[' + goodsIndex + '].cart_num']: parseInt(goodsnum) + 1,
          ['resultList[' + goodsIndex + '].isCanAdd']: true,
          ['resultList[' + goodsIndex + '].isCanReduce']: true,
          cartNum: parseInt(this.data.cartNum) + 1
        })
        this.getCartNum();
        wx.reportAnalytics('addcart_bysearch', {
          goodsname: name,
          addgoodsnum: parseInt(goodsnum) + 1,
          curgoodsnum: goodsnum,
          goodsprice: goodprice,
          cartnum: this.data.cartNum
        });
        this.storageUpdateGoods(curtarget.id, parseInt(goodsnum) + 1, curtarget.categoryid)
      } else {
        this.setData({
          ['resultList[' + goodsIndex + '].isCanAdd']: true,
          ['resultList[' + goodsIndex + '].isCanReduce']: true
        })
        if (res.data.errno == '100012') {
          this.setData({
            showLoginPop: true
          })
        } else {
          common.showErrorToast(res.data.errmsg);
        }

      }
    })
  },
  //商品减1
  reduceCount(e) {
    var curtarget = e.currentTarget.dataset;
    let goodsIndex = curtarget.index;
    let cartList = this.data.resultList;
    let name = curtarget.name;
    let goodprice = curtarget.price;
    let goodsnum = curtarget.goodsnum;
    cartList[goodsIndex].isCanReduce = false;
    this.setData({
      resultList: cartList
    })
    server.postJSON(common.storePath + 'cart/decrease/', {
      "store_id": this.data.storeId,
      "goods_id": curtarget.id,
      "trace_id": ""
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          ['resultList[' + goodsIndex + '].cart_num']: parseInt(goodsnum) - 1,
          ['resultList[' + goodsIndex + '].isCanAdd']: true,
          ['resultList[' + goodsIndex + '].isCanReduce']: true
        })
        this.getCartNum();
        wx.reportAnalytics('addcart_bysearch', {
          goodsname: name,
          removegoodsnum: parseInt(goodsnum) - 1,
          curgoodsnum: goodsnum,
          goodsprice: goodprice,
          cartnum: this.data.cartNum
        });
        this.storageUpdateGoods(curtarget.id, parseInt(goodsnum) - 1, curtarget.categoryid)
      } else {
        console.log('上报失败')
        this.setData({
          ['resultList[' + goodsIndex + '].isCanAdd']: true,
          ['resultList[' + goodsIndex + '].isCanReduce']: true
        })
        this.setData({
          resultList: cartList
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //修改缓存中商品信息
  storageUpdateGoods(goodsid, num, classid) {
    var storeArry = new Array();
    wx.getStorage({
      key: 'updateStoreArry',
      success: res => {
        storeArry = res.data;
        var t = storeArry.find(item => {
          return item.goodsid === goodsid;
        });
        if (t) {
          t.goodsnum = num;
        } else {
          storeArry.push({
            goodsid: goodsid,
            goodsnum: num,
            storeid: this.data.storeId,
            classid: classid
          })
        }
        wx.setStorage({
          key: 'updateStoreArry',
          data: storeArry,
        })
      },
      fail: res => {
        storeArry.push({
          goodsid: goodsid,
          goodsnum: num,
          storeid: this.data.storeId,
          classid: classid
        })
        wx.setStorage({
          key: 'updateStoreArry',
          data: storeArry,
        })

      }

    })
    app.globalData.isDeleteByStore = false;
  },
  //删除历史搜索
  deleteHistoryWords() {
    this.setData({
      showDelPop: true
    })
  },
  confirmDel() {
    wx.removeStorage({
      key: 'historyWordsArray',
      success: res => {
        this.setData({
          showDelPop: false,
          recentWords: []
        })
      }
    })
  },
  cancelDel() {
    this.setData({
      showDelPop: false
    })
  },

  clearKeyword() {
    this.setData({
      showRecentSearch: true,
      searchValue: "",
      resultList: []
    })
    console.log(this.data.resultList)
    this.getHistoryWord();
  },
  onHide() {
    console.log('hide');
    wx.removeStorageSync('goodsNum')
  },
  //前往详情页
  goToProductDetail(e) {
    let goodsId = e.currentTarget.dataset.id;
    let categoryid = e.currentTarget.dataset.categoryid;
    app.globalData.formSceneId = '';
    wx.navigateTo({
      url: '../../pages/shop/productDetail?id=' + goodsId + '&&storeId=' + this.data.storeId + '&&categoryid=' + categoryid
    })
  },
  backToHome() {
    app.globalData.skipType = 0;
    wx.navigateTo({
      url: '../../pages/shop/productsListIndex',
    })
  },
  goToCart() {
    if (this.data.isLogin) {
      app.globalData.cartIndexType = 2;
      wx.navigateTo({
        url: '../../pages/cart/cartIndexSec',
      })
    } else {
      this.setData({
        showLoginPop: true
      })
    }
  },
  getRecommendGoods() {
    server.postJSON(common.storePath + 'store/getrecommendgoods/', {
      "store_id": this.data.storeId,
      "recommend_type": 'like',
      "recommend_num": 10
    }, res => {
      if (res.data.errno == '0') {
        if (res.data.data.length > 0) {
          (res.data.data).forEach((item, index) => {
            item.isCanAdd = true;
            item.isCanReduce = true;
          })
          this.setData({
            recommendGoods: res.data.data
          })
          if (common.compareVersion(wx.getSystemInfoSync().SDKVersion, '1.9.6') >= 0) {
            this.data.recommendGoods.forEach((item, idx) => {
              let intersect = wx.createIntersectionObserver();
              intersect.relativeToViewport().observe('#easy-rec-' + item.goods_id, (res) => {
                intersect.disconnect(); //使用disconnect，使得目标节点只曝光一次
                console.log('曝光#easy-rec-' + item.goods_id);
                server.postJSON(common.storePath + 'store/reportusertrace/', {
                  "store_id": this.data.storeId,
                  "recommend_type": 'like',
                  "list": [{
                    "goods_id": item.goods_id,
                    "trace_id": item.trace_id,
                    "position": idx
                  }]
                }, res => {
                  if (res.data.errno == '0') {
                    console.log('曝光成功')
                  } else {
                    common.showErrorToast(res.data.errmsg)
                  }
                })
              })
            })
          }
        }

      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  //添加为你推荐商品
  addRecommendCart(e) {
    var index = e.currentTarget.dataset.index;
    console.log(index)
    this.setData({
      ['recommendGoods[' + index + '].isCanAdd']: false
    })
    server.postJSON(common.storePath + 'cart/addgoods/', {
      "store_id": this.data.storeId,
      "goods_id": e.currentTarget.dataset.id,
      "trace_id": e.currentTarget.dataset.traceid
    }, res => {
      if (res.data.errno == "0") {
        common.showErrorToast("添加成功");
        this.getCartNum();
        this.setData({
          ['recommendGoods[' + index + '].isCanAdd']: true,
          ['recommendGoods[' + index + '].cart_num']: parseInt(this.data.recommendGoods[index].cart_num) + 1
        })
      } else {
        this.setData({
          ['recommendGoods[' + index + '].isCanAdd']: true
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  addEmpty() {
    console.log('waiting add success')
  },
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      common.checkLogin().then(res => {
        this.setData({
          isDisableLog: false
        })
        if (res.errno == "0") {
          this.setData({
            showLoginPop: false,
            isLogin: true
          })
          wx.setStorage({
            key: "sso",
            data: res.data.sso,
            success: res => {
              this.getRecommendGoods();
            }
          })
          app.globalData.openid = res.data.openid;
          if (JSON.stringify(res.data.member) != "{}") {
            this.storageUserinfo(res.data);
          }
        } else if ((res.errMsg).indexOf('getUserInfo:fail') > -1) {
          this.setData({
            showLoginPop: true
          })
        } else {
          common.showErrorToast(res.errmsg)
        }
      })

    } else {
      this.setData({
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
  },
  showAgreement() {
    wx.navigateTo({
      url: '../../pages/common/agreement'
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false,
      isLogin: false
    })
  }
})